package com.shajj.data;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class DataManager {
	private PersistenceManager persistenceManager;
	private Query singleQuery;
	private Query pageQuery;
	
	private static DataManager instance = new DataManager();

	public static DataManager getInstance() {
		return instance;
	}
	
	private DataManager() {
		persistenceManager = PMF.get().getPersistenceManager();
		singleQuery = persistenceManager.newQuery(Message.class, "id == idParam");
		singleQuery.declareParameters("Long idParam");
		pageQuery = persistenceManager.newQuery(Message.class);
	}
	
	@SuppressWarnings("unchecked")
	public Message get(Long id) {
		List<Message> list = (List<Message>) singleQuery.execute(id);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<Message> getByPage(int start, int size) {
		pageQuery.setRange(start, start + size);
		pageQuery.setOrdering("time desc");
		return (List<Message>) pageQuery.execute();
	}
	
	public void save(Message message) {
		persistenceManager.makePersistent(message);
	}
}
